﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Messhall.Framework.AppFilters
{
    /// <summary>
    /// 返回结果过滤器，统一返回数据格式
    /// </summary>
    public class AppResultFilter : Attribute, IActionFilter
    {
        /// <summary>
        /// 请求时长计时开始
        /// </summary>
        private readonly Stopwatch watch = new Stopwatch();


        /// <summary>
        /// 返回结果执行之前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            watch.Start();//开始  
        }

        /// <summary>
        /// 返回结果执行之后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {

            watch.Stop();
            //根据实际需求进行具体实现
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(new ApiResult { HttpStatus = HttpStatusCode.NotFound, Message = "未找到资源", TimeOut = watch.ElapsedMilliseconds });
                }
                else
                {
                    if (objectResult.Value is ApiResult)
                    {
                        var result = (ApiResult)objectResult.Value;
                        result.TimeOut = watch.ElapsedMilliseconds;
                        context.Result = new ObjectResult(result);
                        return;
                    }
                    context.Result = new ObjectResult(new ApiResult { HttpStatus = HttpStatusCode.OK, Message = "请求成功", Data = objectResult.Value, TimeOut = watch.ElapsedMilliseconds });
                    //判读是否返回的是元组
                    //返回数据并且返回总行数 public async Task<（List<object>,int）> Paging(PagingBaseRequest parameter) { retuen ( new List<object>{ },1000) }
                    if (objectResult.DeclaredType != null && objectResult.DeclaredType.Name == "ValueTuple`2")
                    {
                        dynamic value = objectResult.Value;
                        if (value.Item1 != null)
                        {
                            if (value.Item1 is int)
                            {
                                //返回元组格式（int,List<object>）
                                context.Result = new ObjectResult(new ApiResult { HttpStatus = HttpStatusCode.OK, Message = "请求成功", TimeOut = watch.ElapsedMilliseconds, Data = new { Count = value.Item1, Data = value.Item2 } });
                            }
                            else
                                //返回元组格式（List<object>,int）
                                context.Result = new ObjectResult(new ApiResult { HttpStatus = HttpStatusCode.OK, Message = "请求成功", TimeOut = watch.ElapsedMilliseconds, Data = new { Count = value.Item2, Data = value.Item1 } });
                        }
                    }

                }
            }

        }

    }


    /// <summary>
    /// 数据返回模型基类
    /// </summary>
    public class ApiResult
    {
        /// <summary>
        /// 返回状态码
        /// </summary>
        public virtual HttpStatusCode HttpStatus { get; set; } = HttpStatusCode.OK;

        /// <summary>
        /// 返回数据
        /// </summary>
        public virtual object Data { get; set; }

        /// <summary>
        /// 获取 消息内容
        /// </summary>
        public virtual string Message { get; set; }

        /// <summary>
        /// 执行时长
        /// </summary>
        public virtual long TimeOut { get; set; }
    }
}
